//
//  Y2WebView.m
//  Y2Common
//
//  Created by MacPro on 2021/3/12.
//

#import "Y2WebView.h"
#import "Y2WebViewScriptMessageObject.h"

// webview key path
#define Y2_KP_TITLE @"title"
#define Y2_KP_CAN_GO_BACK @"canGoBack"
#define Y2_KP_CAN_GO_FORWARD @"canGoForward"
#define Y2_KP_ESTIMATED_PROGRESS @"estimatedProgress"

//Message
#define OPK_WMN_INIT @"init"
#define OPK_WMN_EXIT @"exit"

#define OPK_WK_CALLBACK @"callback"

@interface Y2WebView()<Y2WebViewScriptMessageDelegate, WKUIDelegate, WKNavigationDelegate>
@property (nonatomic, strong)Y2WebViewScriptMessageObject *scriptMessageObj;

@property (nonatomic, strong)UIActivityIndicatorView * activityIndicator;
@property (nonatomic, strong)UIButton *failedBackButton;
@end

@implementation Y2WebView

- (instancetype)initWithMessages:(NSArray <NSString *>*)messages {
    _scriptMessageObj = [[Y2WebViewScriptMessageObject alloc] initWithDelegate:self];
    WKUserContentController *userController = [[WKUserContentController alloc] init];
    
    // 注册所有消息
    for (NSString *name in messages) {
        [userController addScriptMessageHandler:_scriptMessageObj name:name];
    }
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.allowsInlineMediaPlayback = NO;
    config.userContentController = userController;
    
    self = [self initWithFrame:CGRectZero configuration:config];
    if (self) {
        self.allowsBackForwardNavigationGestures = YES;
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
        self.UIDelegate = self;
        self.navigationDelegate = self;
        [self addObserver];
        [self initializeComponents];
    }
    return self;
}

- (void)dealloc {
    [self.configuration.userContentController removeAllUserScripts];
    [self removeObserver];
}

#pragma mark - Add subviews
- (void)initializeComponents {
    _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [self addSubview:_activityIndicator];
    
    _failedBackButton = [[UIButton alloc] init];
    [_failedBackButton setTitle:@"加载失败，点击返回" forState:UIControlStateNormal];
    [_failedBackButton setTitleColor:[UIColor systemBlueColor] forState:UIControlStateNormal];
    _failedBackButton.titleLabel.font = [UIFont systemFontOfSize:11];
    [_failedBackButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [_failedBackButton setHidden:YES];
    [self addSubview:_failedBackButton];
}

// 添加约束
- (void)makeConstraints {
    _activityIndicator.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *indicatorCenterX = [NSLayoutConstraint constraintWithItem:_activityIndicator attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    NSLayoutConstraint *indicatorCenterY = [NSLayoutConstraint constraintWithItem:_activityIndicator attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
    NSLayoutConstraint *indicatorWidth = [NSLayoutConstraint constraintWithItem:_activityIndicator attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:0 constant:50];
    NSLayoutConstraint *indicatorHeight = [NSLayoutConstraint constraintWithItem:_activityIndicator attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeHeight multiplier:0 constant:50];
    [self addConstraints:@[indicatorCenterX, indicatorCenterY, indicatorWidth, indicatorHeight]];
    
    
    _failedBackButton.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *backButtonCenterX = [NSLayoutConstraint constraintWithItem:_failedBackButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    NSLayoutConstraint *backButtonCenterY = [NSLayoutConstraint constraintWithItem:_failedBackButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
    NSLayoutConstraint *backButtonWidth = [NSLayoutConstraint constraintWithItem:_failedBackButton attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:0 constant:150];
    NSLayoutConstraint *backButtonHeight = [NSLayoutConstraint constraintWithItem:_failedBackButton attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeHeight multiplier:0 constant:40];
    [self addConstraints:@[backButtonCenterX, backButtonCenterY, backButtonWidth, backButtonHeight]];
}

#pragma mark - Button Selector
- (void)backAction:(UIButton *)sender {
    
}

#pragma mark - Observer
- (void)addObserver {
    [self addObserver:self
                   forKeyPath:Y2_KP_TITLE
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self addObserver:self
                   forKeyPath:Y2_KP_CAN_GO_BACK
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self addObserver:self
                   forKeyPath:Y2_KP_CAN_GO_FORWARD
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self addObserver:self
                   forKeyPath:Y2_KP_ESTIMATED_PROGRESS
                      options:0
                      context:nil];
}


- (void)removeObserver {
    [self removeObserver:self forKeyPath:Y2_KP_TITLE];
    [self removeObserver:self forKeyPath:Y2_KP_CAN_GO_BACK];
    [self removeObserver:self forKeyPath:Y2_KP_CAN_GO_FORWARD];
    [self removeObserver:self forKeyPath:Y2_KP_ESTIMATED_PROGRESS];
}

#pragma mark - Y2WebViewScriptMessageDelegate
- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
    
}

@end
